//
//  LearnController.m
//  GuShiNews
//
//  Created by 丁一 on 2019/8/22.
//  Copyright © 2019 Jones. All rights reserved.
//

#import "LearnController.h"
#import "LearnModel.h"
#import "JCTopic.h"
#import "LearnHomeCell.h"
#import "CenterworkCell.h"
#import "SuiJiViewModel.h"
#import "NewsModel.h"
#import "NewsAction.h"
#import "LearnViewModel.h"
#import "XueXiController.h"
#import "JoneCunChu.h"
#import "MementoCenter.h"
#import "NSObject+MementoCenter.h"
#import "XueXiModel.h"
#import "SearchXueController.h"
#import "HomeLunTVModel.h"
#import "HomeAction.h"
#import "SideNewsViewModel.h"
#import "HomeNewsCell.h"
#import "HHShowView.h"

@interface LearnController ()<JCTopicDelegate,UICollectionViewDataSource,UICollectionViewDelegate,SuijiSideNewsDelegate,GetLearnListDelegate,UISearchBarDelegate,GetHomeSideNewsDelegate>{
    CGFloat    linWH;
}

@property (nonatomic, strong) JCTopic         *Topic;
@property (strong, nonatomic) UIPageControl   *Topicpage;
@property (strong, nonatomic) NSMutableArray  *tempArray;
@property (strong, nonatomic) NSMutableArray  *tempArray_news;

@property (nonatomic, strong) UICollectionView *collectionview;
@property (nonatomic, strong) NSMutableArray   *Good_array;

@property (nonatomic, strong) NSMutableArray   *xue_array;

@property (nonatomic, strong) UISearchBar      *TsearchBar;

@property (nonatomic, strong) NSMutableArray   *tabe_suiji;

@property (nonatomic, strong) UILabel           *zhulabelsuiji;

@end

@implementation LearnController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setnavback];
    self.navigationItem.leftBarButtonItems = nil;
    self.Data_array = [NSMutableArray new];
    
    linWH                          = RECRWITCH/3;
    
    self.tempArray = [NSMutableArray new];
    self.tempArray_news = [NSMutableArray new];
    self.xue_array = [NSMutableArray new];
    self.tabe_suiji = [NSMutableArray new];
    
    JoneCunChu *shuju=[[JoneCunChu alloc] init];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"BannerList"]) {
        [shuju recoverFormStateWithKey:@"BannerList"];
        NSMutableArray *linlist = [NSMutableArray new];
        linlist = shuju.JoneArray;
        [linlist enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NewsModel *modellin = obj;
            [self.tempArray addObject:[NSDictionary dictionaryWithObjects:@[modellin.news_img ,modellin.news_tittle,[NSString stringWithFormat:@"%lu",(unsigned long)idx],@"0",@NO] forKeys:@[@"pic",@"title",@"done",@"order",@"isLoc"]]];
            [self.tempArray_news addObject:modellin];
        }];
    }
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"LearnList"]) {
        [shuju recoverFormStateWithKey:@"LearnList"];
        NSMutableArray *linlist = [NSMutableArray new];
        linlist = shuju.JoneArray;
        [self.Data_array addObjectsFromArray:linlist];
    }
    
    [self.view addSubview:self.TableView];
    
    MJHiCarHeader *header           = [MJHiCarHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadnew)];
    header.automaticallyChangeAlpha    = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden           = YES;
    self.TableView.mj_header          = header;
    self.TableView.mj_header.automaticallyChangeAlpha = YES;
    [self.TableView.mj_header beginRefreshing];
    self.TableView.mj_footer           = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadmore];
    }];
    self.TableView.mj_footer.hidden    = YES;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [UIView new];
    if (section==0) {
        if (!_Topic) {
            _Topic = [[JCTopic alloc]initWithFrame:CGRectMake(10, 44, RECRWITCH-20, RECRWITCH*0.45-44)];
            _Topic.JCdelegate = self;
            _Topic.layer.masksToBounds = YES;
            _Topic.layer.cornerRadius = 10;
            _Topicpage = [[UIPageControl alloc] init];
            _Topicpage.currentPageIndicatorTintColor = [JonesClass stringTOColor:@"#858493"];
            _Topicpage.pageIndicatorTintColor = [JonesClass stringTOColor:@"#cccccc"];
            
            _Topicpage.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.75f, 0.75f);
            _Topicpage.frame = CGRectMake(10-(RECRWITCH-20)/2, RECRWITCH*0.45-90, RECRWITCH-20, 10);
        }
        _Topic.pics = self.tempArray;
        [_Topic upDate];
        [header addSubview:_Topic];
        [header addSubview:_Topicpage];
        
        [header addSubview:self.TsearchBar];

        [header addSubview:self.collectionview];
        
        if (!_zhulabelsuiji) {
            _zhulabelsuiji = [[UILabel alloc] initWithFrame:CGRectMake(0, RECRWITCH*0.45 + (linWH)*2 , RECRWITCH, 45)];
            _zhulabelsuiji.text = @"     最新资讯";
            _zhulabelsuiji.backgroundColor = backColor;
            _zhulabelsuiji.font = [UIFont boldSystemFontOfSize:16];
            _zhulabelsuiji.textColor=NewsotherColor;
            
            CALayer *klines = [CALayer new];
            klines.backgroundColor = NavItemTitleColor.CGColor;
            klines.frame=CGRectMake(10, 0, 3, 45);
            [_zhulabelsuiji.layer addSublayer:klines];
        }
        [header addSubview:_zhulabelsuiji];
    }
    
    return header;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return RECRWITCH*0.45 + (linWH)*2 + 45;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.tabe_suiji.count;
}

#pragma mark - UITableView DataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeNewsCell *cell = [HomeNewsCell cellForTableView:tableView cellForRowAtIndexPath:indexPath];
    cell.Model = [self.tabe_suiji objectAtIndex:indexPath.row];
    return cell;
}

#pragma mark - UITableView Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewsModel *model = [self.tabe_suiji objectAtIndex:indexPath.row];
    return model.news_height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NewsModel *model = [self.tabe_suiji objectAtIndex:indexPath.row];
    [NewsAction Actiontodone:JonesGOTO_NewsInfo view:self dictionary:@{@"model":model}];
    model.IsRead = YES;
    [tableView reloadData];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)loadnew{
    SuiJiViewModel *viewmodel = [[SuiJiViewModel alloc] init:@{@"type":@"1"}];
    viewmodel.delegate =self;
    
    LearnViewModel *lviewmodel = [[LearnViewModel alloc] init:@{@"type":@"1"}];
    lviewmodel.delegate =self;
    
    NSMutableDictionary *postdicf = [NSMutableDictionary new];
    [postdicf setValue:@"0" forKey:@"page"];
    [postdicf setValue:@"100" forKey:@"type"];
    SideNewsViewModel *viewmodelfd = [[SideNewsViewModel alloc] init:postdicf];
    viewmodelfd.delegate = self;
}

- (void)loadmore{
    NewsModel *modellin = [self.tabe_suiji lastObject];
    NSInteger page = [modellin.news_id integerValue];
    
    NSMutableDictionary *postdic = [NSMutableDictionary new];
    [postdic setValue:[NSString stringWithFormat:@"%li",(long)page] forKey:@"page"];
    [postdic setValue:@"100" forKey:@"type"];
    SideNewsViewModel *viewmodel = [[SideNewsViewModel alloc] init:postdic];
    viewmodel.delegate = self;
}


- (void)GetHomeSideNewsSucces:(int)value array:(NSMutableArray *)array page:(NSInteger)page{
    if (value == 1) {
        if (page==0) {
            [self.tabe_suiji removeAllObjects];
        }
        [self.tabe_suiji addObjectsFromArray:array];
        
        if (array.count<15) {
            self.TableView.mj_footer.hidden = YES;
        }else{
            self.TableView.mj_footer.hidden = NO;
        }
    }
    [self.TableView.mj_header endRefreshing];
    [self.TableView.mj_footer endRefreshing];
    [self.TableView reloadData];
}

- (void)SuijiSideNewsSucces:(int)value array:(NSMutableArray *)array page:(NSInteger)page{
    if (value==1) {
        [self.tempArray removeAllObjects];
        [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NewsModel *modellin = obj;
            [self.tempArray addObject:[NSDictionary dictionaryWithObjects:@[modellin.news_img ,modellin.news_tittle,[NSString stringWithFormat:@"%lu",(unsigned long)idx],@"0",@NO] forKeys:@[@"pic",@"title",@"done",@"order",@"isLoc"]]];
            [self.tempArray_news addObject:modellin];
        }];
        [self.TableView.mj_header endRefreshing];
        [self.TableView reloadData];
    }else{
        
        HHShowView *showView = [HHShowView alertTitle:@"网络失败" message:@"亲是否重新加载呢？" ];
        showView.butttonCancelBgColor = [UIColor orangeColor];
        
        [showView addAction:[HHAlertAction actionTitle:@"取消" style:HHAlertActionCancel handler:^(HHAlertAction *action) {
            
        }]];
        [showView addAction:[HHAlertAction actionTitle:@"确定" style:HHAlertActionConfirm handler:^(HHAlertAction *action) {
            [self.TableView.mj_header beginRefreshing];
        }]];
        [showView show];
        
    }
}

- (void)GetLearnListSucces:(int)value array:(NSMutableArray *)array{
    if (value==1) {
        [self.Data_array removeAllObjects];
        [self.Data_array addObjectsFromArray:array];
        [self.TableView.mj_header endRefreshing];
        [self.collectionview reloadData];
        [self.TableView reloadData];
    }
}

-(UICollectionView *)collectionview{
    if (!_collectionview) {
        UICollectionViewFlowLayout *fallLayout = [[UICollectionViewFlowLayout alloc] init];
        fallLayout.scrollDirection             = UICollectionViewScrollDirectionHorizontal;
        fallLayout.itemSize                    = CGSizeMake(linWH, linWH);
        fallLayout.minimumInteritemSpacing     = 0;
        fallLayout.minimumLineSpacing          = 0;
        _collectionview                        = [[UICollectionView alloc] initWithFrame:CGRectMake(0, RECRWITCH*0.45, RECRWITCH,(linWH)*2) collectionViewLayout:fallLayout];
        [_collectionview setDelegate:self];
        [_collectionview setDataSource:self];
        [_collectionview setShowsHorizontalScrollIndicator:NO];
        [_collectionview setShowsVerticalScrollIndicator:NO];
        
        [_collectionview setBackgroundColor:self.view.backgroundColor];
        _collectionview.keyboardDismissMode    = UIScrollViewKeyboardDismissModeOnDrag;
        [_collectionview registerClass:[CenterworkCell class] forCellWithReuseIdentifier:@"CenterworkCell"];
    }
    return _collectionview;
}

-(UISearchBar *)TsearchBar{
    if (!_TsearchBar) {
        _TsearchBar              = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, RECRWITCH, 40)];
        _TsearchBar.placeholder  = @"输入搜索内容";
        _TsearchBar.barTintColor = [JonesClass stringTOColor:@"#f5f5f5"];
        _TsearchBar.delegate     = self;
        _TsearchBar.searchBarStyle  = UISearchBarStyleMinimal;
    }
    return _TsearchBar;
}


- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:NO animated:YES];
    
   [NewsAction Actiontodone:JonesGOTO_NewsSearch view:self dictionary:@{}];
    
    [searchBar resignFirstResponder];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.Data_array.count;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CenterworkCell *cell = (CenterworkCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CenterworkCell" forIndexPath:indexPath];
    LearnModel *model     = [self.Data_array objectAtIndex:indexPath.row];
    cell.Model           = model;
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    LearnModel *model     = [self.Data_array objectAtIndex:indexPath.row];
    
    XueXiController *vc =[XueXiController new];
    vc.model = model;
    vc.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor       = [UIColor clearColor];
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView  didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor       = [UIColor clearColor];
}

#pragma mark - JCDelegate
-(void)currentPage:(int)page total:(NSUInteger)total{
    _Topicpage.numberOfPages = total;
    _Topicpage.currentPage   = page;
}

-(void)didClick:(id)data{
    NewsModel *model = [self.tempArray_news objectAtIndex:[[data objectForKey:@"done"] intValue]];
    [NewsAction Actiontodone:JonesGOTO_NewsInfo view:self dictionary:@{@"model":model}];
}

@end
